package intr.prog.movil;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.format.Time;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class SendSMSActivity extends Activity {
	
	final int PICK_PATENT_DIALOG_ID = 1001;
	final int PICK_HOUR_DIALOG_ID = 1002;

	private SharedPreferences preferences;
	
	private ArrayList<String> spinnerArray;
	private int patentQuantity;
	private Spinner patentInput;
	private Spinner hourInput;
	private Dialog patentDialog;
	private String formatted_address;
	private LocationManager locationManager;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        SendSMSActivity.this.findViewById(R.id.resultLayout).setVisibility(LinearLayout.GONE);
        SendSMSActivity.this.findViewById(R.id.locationTitle).setVisibility(LinearLayout.GONE);
        SendSMSActivity.this.findViewById(R.id.locationResult).setVisibility(LinearLayout.GONE);
      
        findViewById(R.id.getlocationbutton).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//Disable the Button to avoid multi-clic
				findViewById(R.id.getlocationbutton).setEnabled(false);
				SendSMSActivity.this.findViewById(R.id.resultLayout).setVisibility(LinearLayout.GONE);
				SendSMSActivity.this.findViewById(R.id.locationTitle).setVisibility(LinearLayout.VISIBLE);
		        SendSMSActivity.this.findViewById(R.id.locationResult).setVisibility(LinearLayout.VISIBLE);
				((TextView)findViewById(R.id.locationResult)).setText(SendSMSActivity.this.getString(R.string.location_searching));
				
				locationManager = (LocationManager)SendSMSActivity.this.getSystemService(Context.LOCATION_SERVICE);
				locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new MyLocationListener());

			}
		});
        
        findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog(PICK_PATENT_DIALOG_ID);
			}
		});
        
        findViewById(R.id.button2).setOnClickListener(new OnClickListener() {	
			@Override
			public void onClick(View v) {
				SendSMSActivity.this.finish();
			}
		});
    }
    
    private void setParkingStatusGUI(boolean isRestricted){
    	if (!isRestricted) {
    		ImageView parkingLogo = (ImageView)SendSMSActivity.this.findViewById(R.id.parkingImage);
			parkingLogo.setImageResource(R.drawable.allowed_parking);
			TextView parkingLegend = (TextView)SendSMSActivity.this.findViewById(R.id.parkinglegend);
			parkingLegend.setText(R.string.allowed_parking);
    	} else {
    		ImageView parkingLogo = (ImageView)SendSMSActivity.this.findViewById(R.id.parkingImage);
			parkingLogo.setImageResource(R.drawable.restricted_parking);
			TextView parkingLegend = (TextView)SendSMSActivity.this.findViewById(R.id.parkinglegend);
			parkingLegend.setText(R.string.restricted_parking);
    	}		
    }
    
    private void setTimeStatusGUI(boolean isRestricted){
    	if (!isRestricted) {
    		ImageView parkingLogo = (ImageView)SendSMSActivity.this.findViewById(R.id.timeImage);
			parkingLogo.setImageResource(R.drawable.allowed_time);
			TextView parkingLegend = (TextView)SendSMSActivity.this.findViewById(R.id.timelegend);
			parkingLegend.setText(R.string.allowed_time);
    	} else {
    		ImageView parkingLogo = (ImageView)SendSMSActivity.this.findViewById(R.id.timeImage);
			parkingLogo.setImageResource(R.drawable.restricted_time);
			TextView parkingLegend = (TextView)SendSMSActivity.this.findViewById(R.id.timelegend);
			parkingLegend.setText(R.string.restricted_time);
    	}		
    }
    
    private void setParkingResult(boolean isRestricted){
    	if (isRestricted){
    		((TextView)SendSMSActivity.this.findViewById(R.id.parkinglegendresult)).setText(R.string.restricted_parking_legend_result);
			((TextView)SendSMSActivity.this.findViewById(R.id.parkinglegendresult)).setTextColor(Color.rgb(245, 153, 38));
    	}else {
    		((TextView)SendSMSActivity.this.findViewById(R.id.parkinglegendresult)).setText(R.string.allowed_parking_legend_result);
			((TextView)SendSMSActivity.this.findViewById(R.id.parkinglegendresult)).setTextColor(Color.rgb(0, 236, 60));
    	}
    }
    
    private boolean isRestrictedTime(){
    	Time now = new Time();
    	now.setToNow();
    	if (now.weekDay>6){
    		return false;
    	}else if(now.weekDay==6){
    		return ((Integer.valueOf(getString(R.string.start_time))-1<now.hour) && (now.hour<(Integer.valueOf(getString(R.string.middle_time)))));
    	}else {
    		return ((Integer.valueOf(getString(R.string.start_time))-1<now.hour) && (now.hour<(Integer.valueOf(getString(R.string.end_time)))));
    	}
    }
    
    private ArrayList<String> getPatentSpinnerArray(){
		if (spinnerArray == null){
			spinnerArray = new ArrayList<String>();
			spinnerArray.addAll(getPatentsFromSharedPreferences());
			spinnerArray.add(getString(R.string.new_patent));
		}
		return spinnerArray;
	}
    
    private List<String> getPatentsFromSharedPreferences(){
    	List<String> list = new ArrayList<String>(); 
    	boolean eof = false;
    	int i=0;
		while (!eof){
			String auxPatent = preferences.getString("patent"+i, null);
			if (auxPatent == null)
				eof = true;
			else{
				list.add(auxPatent);
				i++;
			}
		}
		patentQuantity = i;
		return list;
    }
    
    private OnItemSelectedListener getPatentOnItemSelectedListener(){
    	return new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				String pickedPatent = spinnerArray.get(position);
		        if (pickedPatent.equals(SendSMSActivity.this.getString(R.string.new_patent))){
		        		patentDialog.hide();
			        	final EditText textInput = new EditText(SendSMSActivity.this);
			        	new AlertDialog.Builder(SendSMSActivity.this)
			            .setTitle(getString(R.string.new_patent))
			            .setView(textInput)
			            .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			                public void onClick(DialogInterface dialog, int whichButton) {
			                    Editable value = textInput.getText(); 
			                   
			                    getPatentSpinnerArray().add(0,value.toString());

	            	        	ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(SendSMSActivity.this, android.R.layout.simple_spinner_item, getPatentSpinnerArray());
	            	    		spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
	            	    		patentInput.setAdapter(spinnerArrayAdapter);
	            	    		patentDialog.show();
			                }
			            }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			                public void onClick(DialogInterface dialog, int whichButton) {
			                	
			                	ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(SendSMSActivity.this, android.R.layout.simple_spinner_item, getPatentSpinnerArray());
	            	    		spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
	            	    		patentInput.setAdapter(spinnerArrayAdapter);
	            	    		patentDialog.show();
			                }
			            }).show();
		        } 	
			}
			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		};
    }
    
    private Dialog getPatentToPark(){
    	patentInput = new Spinner(SendSMSActivity.this);
    	ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getPatentSpinnerArray());
		spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
		patentInput.setAdapter(spinnerArrayAdapter);
		patentInput.setOnItemSelectedListener(getPatentOnItemSelectedListener());
    	patentDialog = new AlertDialog.Builder(SendSMSActivity.this)
        .setTitle(getString(R.string.patent_promt))
        .setView(patentInput)
        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            	showDialog(PICK_HOUR_DIALOG_ID);
            }
        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            	
            }
        }).create();
    	
    	return patentDialog;
    }
    
    private Dialog getTimeToPark(){
    	hourInput = new Spinner(SendSMSActivity.this);
    	ArrayAdapter<CharSequence> spinnerArrayAdapter = ArrayAdapter.createFromResource(
    	        this, R.array.hours_array, android.R.layout.simple_spinner_item);
    	hourInput.setAdapter(spinnerArrayAdapter);
    	Dialog hourDialog = new AlertDialog.Builder(patentDialog.getContext())
        .setTitle(getString(R.string.hour_promt))
        .setView(hourInput)
        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            	System.out.println("hour selected: "+hourInput.getSelectedItem().toString());
            	System.out.println("patent selected: "+patentInput.getSelectedItem().toString());
            	
            	SendSMSActivity.this.persistPatentSelected();
            	SendSMSActivity.this.sendSMS();
            }
        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            	System.out.println("hour input: canceled");
            }
        }).create();
    	
    	return hourDialog;
    }
    
    private void deleteAllPatents(){
    	boolean eof = false;
    	int i=0;
    	SharedPreferences.Editor editor = preferences.edit();
    	while (!eof){
    		String auxPatent = preferences.getString("patent"+i, null);
			if (auxPatent == null)
				eof = true;
			else{
				editor.putString("patent"+i, null);	
				i++;
			}	
        editor.commit();
    	}
    }
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case PICK_PATENT_DIALOG_ID:
        	return getPatentToPark();
        case PICK_HOUR_DIALOG_ID:
        	return getTimeToPark();
        }
        return null;
    }
    
    public boolean onCreateOptionsMenu(Menu menu){
        MenuInflater inflater=getMenuInflater();
        inflater.inflate(R.menu.send_sms_menu,menu);
        return true;
    }
	
	public boolean onOptionsItemSelected (MenuItem item){
        switch (item.getItemId()){
            case R.id.clearPatentHistory:
            	AlertDialog.Builder builder = new AlertDialog.Builder(this);
            	builder.setMessage(getString(R.string.clear_patent_history_confirm))
            	       .setCancelable(false)
            	       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            	           public void onClick(DialogInterface dialog, int id) {
            	               deleteAllPatents(); 
            	           }
            	       })
            	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
            	           public void onClick(DialogInterface dialog, int id) {
            	                dialog.cancel();
            	           }
            	       });
            	AlertDialog alert = builder.create();
            	alert.show();
            	return true;
            default:
            	return super.onOptionsItemSelected(item);
        }   
    }
	
	private void persistPatentSelected(){
		if (!getPatentsFromSharedPreferences().contains(patentInput.getSelectedItem())){
		SharedPreferences.Editor editor = preferences.edit();
		editor.putString("patent"+patentQuantity, patentInput.getSelectedItem().toString());	
	    editor.commit();
	    patentQuantity++;
		}
	}
	
	private void sendSMS(){
		SmsManager sms = SmsManager.getDefault();
		Toast toast = null;
		try{
			sms.sendTextMessage(getString(R.string.system_phone_number), null, patentInput.getSelectedItem().toString()+" "
					+ValidLocation.getInstance().getStreetKey(ValidLocation.getInstance().getStreetName(formatted_address))+" "
					+ValidLocation.getInstance().getStreetHeight(formatted_address)+" "+hourInput.getSelectedItem().toString(), null, null);
			toast = Toast.makeText(getApplicationContext(), getString(R.string.sucsess_sms_toast), 3);
			toast.show();
		}catch(Exception e){
			toast = Toast.makeText(getApplicationContext(), getString(R.string.fail_sms_toast), 3);
			toast.show();
		}
	}
	
	
	private class MyLocationListener implements LocationListener{

		@Override
		public void onLocationChanged(Location location) {
			try {
			 HttpClient client = new DefaultHttpClient();
		     HttpGet request = new HttpGet();
		     double lat = location.getLatitude();
		     double lng = location.getLongitude();
		     String url = "http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=false";
		     request.setURI(new URI(url));
		     HttpResponse response = client.execute(request);
		     BufferedReader bf=new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			
		     StringBuilder builder = new StringBuilder();
		     for (String line = null; (line = bf.readLine()) != null;) {
		    	 builder.append(line).append("\n");
		     }
		     JSONArray resultsArray = new JSONObject(builder.toString()).getJSONArray("results");							
			 formatted_address = resultsArray.getJSONObject(0).getString("formatted_address");
			 
			 ((TextView)SendSMSActivity.this.findViewById(R.id.locationResult)).setText(formatted_address.split(",")[0]);
			 SendSMSActivity.this.findViewById(R.id.resultLayout).setVisibility(LinearLayout.VISIBLE);
			 
			 //remove from the service listener
			 locationManager.removeUpdates(this);
			 
			 ValidLocation vl = ValidLocation.getInstance();
			 boolean notAFreeParkingZone = !vl.isFreeParkingZone(formatted_address);
			 SendSMSActivity.this.findViewById(R.id.button1).setEnabled(notAFreeParkingZone && isRestrictedTime());
			 setParkingStatusGUI(notAFreeParkingZone);
			 setTimeStatusGUI(isRestrictedTime());
			 setParkingResult(notAFreeParkingZone && isRestrictedTime());
			 
			 //enable the button again
			 findViewById(R.id.getlocationbutton).setEnabled(true);
			 
			 } catch (Exception e) {
				 System.out.print(e);
			 }	
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			
		}
		
		@Override
		public void onProviderEnabled(String provider) {
			
		}
		
		@Override
		public void onProviderDisabled(String provider) {
			
		}
		
	}
}